

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <boost/threadpool.hpp>

using namespace std;
using namespace boost::threadpool;

int task_int_23(int t) {

    boost::this_thread::sleep(boost::posix_time::seconds(t));
    cout << "task_int_sleep()" << t << std::endl;
    return t;
}


//R为任务函数的返回值类型
template<class R>
class callback_task {
    typedef boost::function<void(R)> callback;
    typedef boost::function<R()> function;

private:
    callback c_;
    function f_;

public:
    //F: 任务执行函数 C：结果回调函数
    template<class F, class C>
    callback_task(F f, C c) {
        f_ = f;
        c_ = c;
    }

    void operator()() {
        c_(f_());
    }
};


//task_int_23的结果回调函数
void callback(int k) {
    cout << "get callback value:" << k << endl;
}


class Creater {
public:
    Creater() {
        std::cout << __FUNCTION__ << " " << __LINE__ << std::endl;
    }
    void operator()(){
        std::cout << __FUNCTION__ << " " << __LINE__ << std::endl;
    }

    static void callbackCCC(int k) {
        cout << "CCCC  get callback value:" << k << endl;
    }
};

int main() {

    pool tp(2);

    future<int> res = schedule(tp, (boost::function<int()>) boost::bind(&task_int_23, 1));  // 只接受无参thread入口
    res.wait();
    cout << "get res value:" << res.get() << endl;

    Creater tmpClass();
    tp.schedule(Creater());

//通过回调的形式获取任务的返回值
    tp.schedule(callback_task<int>(boost::bind(&task_int_23, 1), &callback));
    tp.schedule(callback_task<int>(boost::bind(&task_int_23, 2), &callback));
    tp.schedule(callback_task<int>(boost::bind(&task_int_23, 3), &Creater::callbackCCC));
//    callback_task<int>(boost::bind(&task_int_23,1), &callback)();
    cout << "T1" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    cout << "T2" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    cout << "T3" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    cout << "T4" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(1));
}


